<template>
  <div class="list">
    <div class="toper">
      <!-- <SafeTop :toperMessage="toperMessage" /> -->
      <Search @search="(value: string) => {
        data.search = value;
        event.getUserList();
      }" />
    </div>
    <div class="userList">
      <List ref="userList" :list="data.userList" @click="event.changeUser" />
    </div>
  </div>

</template>
<!-- <div class="conversation"> -->
<!-- </div> -->
<script setup lang="ts">
import { getJargon, getMessage, getUserList } from '@/api';
import { type IData } from '@/components/user-list/interface';
import { nextTick, onMounted, onUnmounted, reactive, ref, watch } from 'vue';
import Search from '../search/Search.vue';
import List from '../list/List.vue';
import { useRouter } from 'vue-router';

// import ChatPage from '../chatwindow/ChatPage.vue';


// 用于传递的路由对象
const chat = ref()
const router = useRouter()

const props = defineProps({
  type: {
    type: String,
    default: '',
  },
  followTime: {
    type: String,
    default: '',
  },
});

const userList = ref();
const toperMessage = ref('会话')

const data: IData = reactive({
  self: {},
  search: '',
  userList: [],
  historyMessage: [],
  jargon: {},
  userComment: [],
  defaultTabbar: 0,
  userType: [
    { name: '潜在客户', value: 0 },
    { name: '意向客户', value: 1 },
    { name: '成交客户', value: 2 },
    { name: '黑名单', value: 3 },
  ],
});

const event = {
  // 获取用户列表
  async getUserList() {
    data.userList = await getUserList({
      keyword: data.search,
      type: props.type,
      follow_time: props.followTime,
    });
  },
  // 获取历史聊天记录
  async getHistoryMessage() {
    data.historyMessage = await getMessage({
      conversation_id: data.self['id'],
    });
  },
  // 切换用户
  async changeUser(index: number, item: Record<string, any>) {

    const toperMessage = item['to_name'] + ' · ' + item['from_name'].slice(0, 2)

    document.title = toperMessage;
    // 这里打印的是被点击的用户对话列表
    // console.log(item);
    data.self = item;
    data.userComment = [];

    // 每隔一段事件获取历史消息
    if (data.historyMessagePollTimer) {
      clearInterval(data.historyMessagePollTimer);
    }
    data.historyMessage = [];
    await event.getJargon();
    await event.getHistoryMessage();
    // console.log(data.historyMessage);

    // 在浏览器中储存数据 JSON.stringify()是转字符串
    // 这里仅储存用户列表对应的id 避免数据太多而造成的卡顿
    localStorage.setItem("selfId", JSON.stringify(data.self.id))
    localStorage.setItem('self', JSON.stringify(data.self))

    // 点击切换到路由chatPage，replace表示是否以新的页面为历史页面 表示否
    router.push({ name: 'chatPage', replace: false })

    data.historyMessagePollTimer = setInterval(() => {
      event.getHistoryMessage();
    }, 3000);
  },
  // 获取常用语
  async getJargon() {
    const jargon = await getJargon();
    data.jargon = {};
    jargon.forEach(item => {
      const key = item['name'] as string;
      const contents = item['info'].map(
        (ite: Record<string, string>) => ite['content']
      );
      data.jargon[key] = contents;
    });
  },
};

watch(
  () => [props.type, props.followTime],
  () => {
    data.self = {};
    data.userComment = [];
    data.historyMessage = [];
    if (userList.value) {
      userList.value.reset();
    }
    clearInterval(data.historyMessagePollTimer);
    event.getUserList();
  }
);

onMounted(() => {
  event.getUserList();
  data.userListPollTimer = setInterval(async () => {
    event.getUserList()
  }, 1000);
});

onUnmounted(() => {
  clearInterval(data.userListPollTimer);
  clearInterval(data.historyMessagePollTimer);
});
</script>

<style>
.list {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.toper {
  height: 50px;
  width: 100%;
}

.userList {
  flex: 1;
  width: 100%;
  /* height: calc(100vh - 50px); */
  overflow-y: auto;
}
</style>